package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import com.itheima.health.util.ValidateCodeUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    // 生产验证码
    @PostMapping("/validateCode/send")
    public Result code(String type,String telephone){
        if (telephone == null){
            return new Result(false, MessageConst.SEND_VALIDATECODE_FAIL);
        }
        // 生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //type为ORDER的是订单预约的验证码发送
        if (type.equals("ORDER")){
            // 存到redis中
            redisTemplate.opsForValue().set(RedisConst.VALIDATE_CODE_PREFIX+"_ORDER_"+telephone,code,3, TimeUnit.MINUTES);
            System.out.println("订单套餐预约的验证码是:" + code);
            return new Result(true,MessageConst.SEND_VALIDATECODE_SUCCESS,"发送的验证码是:" + code);
        }
        // 存到redis中
        redisTemplate.opsForValue().set(telephone,code,3, TimeUnit.MINUTES);
        System.out.println("验证码是:" + code);
        return new Result(true,MessageConst.SEND_VALIDATECODE_SUCCESS);
    }
    // 手机登录
    @PostMapping("/login/smsLogin")
    public Result login(@RequestBody Map map){
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(validateCode)){
            return new Result(false,MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        Object code = redisTemplate.opsForValue().get(telephone);
        if (code == null&&(!code.equals(validateCode))){
            return new Result(false,MessageConst.VALIDATECODE_ERROR);
        }
        return new Result(true,MessageConst.LOGIN_SUCCESS);

    }

}
